/*
 * Copyright (C) 2000-2008 Jens Nixdorf and various contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies of the Software, its documentation and marketing & publicity
 * materials, and acknowledgment shall be given in the documentation, materials
 * and software packages that this Software was used.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package org.mopore.jat;

import java.awt.AWTException;
import java.awt.SystemTray;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URISyntaxException;
import java.net.URL;

import javax.swing.UIManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import org.mopore.jat.gui.SysTrayProxy;
import org.mopore.jat.plugin.IPluginContextInternal;
import org.mopore.jat.plugin.PluginEngine;
import org.mopore.jat.plugin.TerminatedDelegator;

public class Main {

	private static final String CAN_NOT_GET_APPLICATION_DIRECTORY = "Can not get application directory";
	private static final String EXCEPTION_ON_TOPLEVEL_NOT_CAUGHT = "Exception on toplevel not caught.";
	
	public static final File PLUGINS_DIR = new File( getApplicationDir(), "plugins" );
	public static final File LOGS_DIR = new File( getApplicationDir(), "logs" );
	public static final File META_DIR = new File( getApplicationDir(), "meta" );
	public static final File TMP_DIR = new File( getApplicationDir(), "tmp" );
	
	private static final File[] directories = new File[] {
		PLUGINS_DIR,
		LOGS_DIR,
		META_DIR,
		TMP_DIR
	};
	
	
	public static void main(String[] args){
		Log log = LogFactory.getLog( Main.class.getName() );
		try {
			
			UIManager.setLookAndFeel(
					UIManager.getSystemLookAndFeelClassName());
			
			assertDirectories();
			configureLogFile();
	
			log.info( "Bootstrapping..." );
	
			// preparing delegators
			TerminatedDelegator terminatedDelegator = new TerminatedDelegator();
			
			// preparing tray icon
			SystemTray tray = SystemTray.getSystemTray();
			SysTrayProxy sysTrayProxy = new SysTrayProxy();
	
			// preparing plugin engine
			log.info( "Creating plugin engine..." );
			PluginEngine pluginEngine = new PluginEngine( sysTrayProxy );
			log.info( "Getting plugin context..." );
			IPluginContextInternal pluginContext =
				pluginEngine.getPluginContextInternal();
			sysTrayProxy.attachPluginContext( pluginContext );
			sysTrayProxy.attachListeners( terminatedDelegator );
			log.info( "Running plugins..." );
			pluginEngine.runPlugins();
			
			try {
				sysTrayProxy.attach( tray );
				sysTrayProxy.initPopupMenu();
			} catch (AWTException e) {
				log.error("TrayIcon could not be added.", e);
				throw e;
			}
			log.info( "BOOTSTRAP INITIATED." );
		}
		catch (Exception e){
			log.fatal( EXCEPTION_ON_TOPLEVEL_NOT_CAUGHT, e );
			throw new InternalError(EXCEPTION_ON_TOPLEVEL_NOT_CAUGHT);
		}
	}

	
	private static void configureLogFile() throws IOException {
		
		RollingFileAppender fileAppender = new RollingFileAppender();

		fileAppender.setName( "LOGFILE" );
		
		File appDir = getApplicationDir();
		File logDir = new File( appDir, "logs" );
		File logFile = new File( logDir, "mopore-togo.log" );
		fileAppender.setAppend( true );
		Writer writer = new FileWriter( logFile );
		fileAppender.setWriter( writer );
		fileAppender.setMaxFileSize( "5MB" );
		
		Layout layout = new PatternLayout( "%-5p %d{HH:mm:ss,SSS} [%C{1}]: %m%n" );
		fileAppender.setLayout( layout );
		
		Logger.getRootLogger().addAppender( fileAppender );
		
	}


	private static void assertDirectories() {
		for ( File  directory : directories ) {
			if ( ! directory.exists() ) {
				directory.mkdir();
			}
		}
	}
	
	
	
	public static File getApplicationDir() {
		
		final Log log = LogFactory.getLog( Main.class.getName() );
		
		URL url = 
			Main.class.getProtectionDomain().getCodeSource().getLocation();
		File file ;
		try {
			file = new File( url.toURI() );
			return file.getParentFile();
		} catch (URISyntaxException e) {
			log.error( CAN_NOT_GET_APPLICATION_DIRECTORY, e );
			throw new InternalError( CAN_NOT_GET_APPLICATION_DIRECTORY );
		}
	}

}
